package com.hbnu.dao;
import com.hbnu.entity.UserFile;
import com.hbnu.entity.User;
import com.hbnu.tools.UserFileTool;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;


public class UserDao extends JDBC{
    //用户名查重
    public  boolean checkUser(String user) {
        try (PreparedStatement preparedStatement = getPreparedStatement(
                "select 1 from users where user_name = ?"
        )){
            preparedStatement.setString(1,user);
            return preparedStatement.executeQuery().next();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //登录检查
    public User check(String userName, String password) {
        try(PreparedStatement statement=getPreparedStatement(
                "select user_id,created_time,logon_time,fid,size,space from users where user_name= ? and user_password= ? and is_deleted=0;"
        )){
            statement.setString(1,userName);
            statement.setString(2,password);
            ResultSet resultSet = statement.executeQuery();
            if(resultSet.next()){
                User user=new User();
                user.setUid(resultSet.getString(1));
                user.setCreated_time(resultSet.getTimestamp(2).toLocalDateTime());
                user.setLogon_time(resultSet.getTimestamp(3).toLocalDateTime());
                user.setFolder_id(resultSet.getInt(4));
                user.setSize(resultSet.getLong(5));
                user.setSpace(resultSet.getLong(6));
                return user;
            }else
                return null;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //  自己到了，父级还没到，所有不能直接生成地址索引，先全部保存
    public Map<Integer, UserFile> getUserFileMap(String uid, int rootFid) {
       //排除了根id
        try(PreparedStatement statement=getPreparedStatement(
                "select fid,pid,fname,file_id,is_file from files_folders where user_id= ? and fid != ? and is_deleted=0;"
        )){
            statement.setString(1,uid);
            statement.setInt(2,rootFid);
            ResultSet resultSet = statement.executeQuery();
            return UserFileTool.initUserFileMap(resultSet);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    //注册方法
    public void register(String uuid, String userName, String pwd) {
        String insertUser = "insert into users(user_id,user_name,user_password,created_time,logon_time) values(?,?,?,now(),now());";
        String insertRoot = "insert into files_folders(user_id,fname,created_time) values(?,'~',now());";
        String updateUser = "update users set fid = ? where user_id = ?;";
        try (PreparedStatement insertUserStatement=getPreparedStatement(insertUser);
             PreparedStatement insertRootStatement=getPreparedStatement0(insertRoot);
             PreparedStatement updateUserStatement=getPreparedStatement(updateUser)) {
             connection.setAutoCommit(false);

            insertUserStatement.setString(1,uuid);
            insertUserStatement.setString(2,userName);
            insertUserStatement.setString(3,pwd);
            int i = insertUserStatement.executeUpdate();
            if (i<0) {
                throw new SQLException("数据库异常");
            }
            // 获取文件的主键
            insertRootStatement.setString(1,uuid);
            insertRootStatement.executeUpdate();
            ResultSet resultSet = insertRootStatement.getGeneratedKeys();
            if (!resultSet.next()) {
                throw new SQLException("Failed to retrieve A's ID");
            }
            int fid = resultSet.getInt(1);
            //更新fid
            updateUserStatement.setInt(1,fid);
            updateUserStatement.setString(2,uuid);
            i = updateUserStatement.executeUpdate();
            if (i<0) {
                throw new SQLException("数据库异常");
            }
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            try {
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }


    }

    //更新登录日期
    public void updateTime(String uid) {
        try(PreparedStatement statement=getPreparedStatement(
                "update users set logon_time = now() where user_id = ?;"
        )){
            statement.setString(1,uid);
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //修改存储大小
    public void updateAddSize(String uid, long size) {
        updateSize(uid,size,"+");
    }

    public void updateReduceSize(String uid, long size) {
        updateSize(uid,size,"-");
    }

    public void updateSize(String uid, long size,String str) {
        try(PreparedStatement preparedStatement=getPreparedStatement(
                "update users set size = size "+str+" ? where user_id = ?;"
        )){
            preparedStatement.setLong(1,size);
            preparedStatement.setString(2,uid);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

}
